<template>
  <div class="app-container">
    <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="100px" style="width: 400px;">
      <el-form-item label="原密码" prop="password">
        <el-input v-model="dataForm.password" type="password" maxlength="12"/>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="dataForm.newPassword" type="password" auto-complete="off" maxlength="30"/>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="dataForm.confirmPassword" type="password" auto-complete="off" maxlength="30"/>
      </el-form-item>
    </el-form>
    <div v-permission="['admin:editCurrentPwd']" style="margin-left:100px;">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="change">确定</el-button>
    </div>
  </div>
</template>

<script>
import { AdminService } from '@/api/AdminService'
import Notify from '@/utils/notify'

export default {
  name: 'ChangePassword',
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码!'))
      } else {
        callback()
      }
    }
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码!'))
      } else if (value !== this.dataForm.newPassword) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      dataForm: { password: '', newPassword: '', confirmPassword: '' },
      rules: {
        password: [
          { required: true, message: '旧密码不能为空!', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '新密码不能为空!', trigger: 'blur' },
          { min: 6, message: '新密码最小6位!', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '确认密码不能为空!', trigger: 'blur' },
          { min: 6, message: '新密码最小6位!', trigger: 'blur' },
          { validator: validatePass2, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    cancel() {
      this.dataForm = {
        password: '',
        newPassword: '',
        confirmPassword: ''
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    change() {
      this.$refs['dataForm'].validate(valid => {
        if (!valid) {
          return
        }
        AdminService.editPwd(this.dataForm)
          .then(() => {
            Notify.success(this, '修改密码成功!')
            this.$store.dispatch('LogOut').then(() => {
              location.reload()
            })
          })
      })
    }
  }
}
</script>
